package com.letoken.platform.pub.util;

import com.letoken.platform.pub.constant.EmailConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class EmailUtil {

    /**
     * 发送邮件
     * @param emailTos 分号分隔
     * @param subject 标题
     * @param content 内容
     * @return
     */
    public static boolean sendEmail(String emailTos, String subject, String content) {
        try {

            HtmlEmail email = new HtmlEmail();//不用更改

            for(String emailTo: emailTos.split(";|,")){
                if (!isEmail(emailTo)) {
                    throw new Exception("请输入正确的邮件地址!");
                }
                else {
                    email.addTo(emailTo);// 收件地址
                }
            }

            email.setHostName(EmailConstant.HOST_NAME);//需要修改，126邮箱为smtp.126.com,163邮箱为163.smtp.com，QQ为smtp.qq.com
            email.setCharset("UTF-8");
            email.setSmtpPort(465);
            email.setSSLOnConnect(true);
            email.setAuthentication(EmailConstant.EMAIL_POST_ADDRESS, EmailConstant.AUTH_CODE);//此处填写邮箱地址和客户端授权码

            email.setFrom(EmailConstant.EMAIL_POST_ADDRESS, "letokenlabs");//此处填邮箱地址和用户名,用户名可以任意填写
            email.setSubject(subject);//此处填写邮件名，邮件名可任意填写
            email.setMsg(content);//此处填写邮件内容

            email.send();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("sendEmail error! to [{}], subject [{}], cnt [{}]", emailTos, subject, content);
            return false;
        }
    }

    public static boolean isEmail(String email) {
        return true; //email.matches("\\w+@\\w+.com");
    }
}
